package site.shihuan.helpdesk.im.command.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import site.shihuan.helpdesk.common.model.Constants;
import site.shihuan.helpdesk.common.model.JwtUser;
import site.shihuan.helpdesk.im.message.BaseMessage;
import site.shihuan.helpdesk.im.command.BaseCommand;
import site.shihuan.helpdesk.im.SessionContextHolder;
import site.shihuan.helpdesk.im.exception.CommandException;
import site.shihuan.helpdesk.im.message.impl.ChatMessage;
import site.shihuan.helpdesk.im.manager.ContactManager;
import site.shihuan.helpdesk.im.manager.MessageManager;
import site.shihuan.helpdesk.im.model.po.SvcRuContactPO;

import javax.websocket.Session;

/**
 * ChatCommand.
 *
 * @author 周世焕
 * @Date 2021/2/2 21:18
 */
@Slf4j
@Component
public class ChatCommand implements BaseCommand {

    @Autowired
    private SessionContextHolder sessionContextHolder;

    @Autowired
    private MessageManager messageManager;

    @Autowired
    private ContactManager contactManager;

    @Override
    public void execute(Session session, BaseMessage message) throws CommandException {
        ChatMessage chatMessage = (ChatMessage)  message;
        JwtUser jwtUser = sessionContextHolder.getUser(session);
        chatMessage.setSender(jwtUser.getUid());
        chatMessage.setTenantId(jwtUser.getTenantId());
        chatMessage.setDate(System.currentTimeMillis());
        log.debug("ChatMessage:{}",message);
        updateLatestMsg(jwtUser,chatMessage);
        messageManager.createMessage(chatMessage);
        try {
            sessionContextHolder.sendMessage(chatMessage,chatMessage.getReceiver());
        }catch (Exception e) {
            log.debug("",e);
            throw new CommandException(CommandException.MSG_SEND_ERROR);
        }
    }

    private boolean checkPermission(){
        return false;
    }

    /**
     * 更新最新一条消息到SvcRuContact
     * @param jwtUser
     * @param chatMessage
     */
    private void updateLatestMsg(JwtUser jwtUser,ChatMessage chatMessage){
        String visitorId = null;
        String clerkId = null;
        String tenantId = jwtUser.getTenantId();
        if(Constants.ROLE_VISITOR.equals(jwtUser.getRole())){
            visitorId = chatMessage.getSender();
            clerkId = chatMessage.getReceiver();
        }else{
            visitorId = chatMessage.getReceiver();
            clerkId = chatMessage.getSender();
        }
        SvcRuContactPO svcRuContactPO = new SvcRuContactPO();
        svcRuContactPO.setVisitorId(visitorId);
        svcRuContactPO.setClerkId(clerkId);
        svcRuContactPO.setContactId(chatMessage.getContactId());
        svcRuContactPO.setLatestMsg(chatMessage.getMsg());
        svcRuContactPO.setLatestMsgTime(chatMessage.getDate());
        contactManager.updateLatestMsg(svcRuContactPO);
    }
}
